package org.ee.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ee.core.ProtocolDetectHandler;
import org.ee.core.exception.ExceptionHandler;
import org.ee.properties.NettyIdle;
import org.ee.protocol.ProtocolDecoder;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 初始化Channel
 * 也可以使用内部类进行初始化
 * bootstrap.group(bossGroup, workerGroup)
 * .channel(NioServerSocketChannel.class)
 * .childHandler(new ChannelInitializer<SocketChannel>() {
 *
 * @Override protected void initChannel(SocketChannel socketChannel) throws Exception {
 * //使用 IdleStateHandler 进行心跳检测
 * socketChannel.pipeline().addLast(new IdleStateHandler(180, 0, 0, TimeUnit.SECONDS));
 * socketChannel.pipeline().addLast(new MyProtocolDecoder());
 * socketChannel.pipeline().addLast(new MyNettyServerHandler());
 * //socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
 * <p>
 * <p>
 * }
 * });
 * @Author jokr
 * @Date 2025/8/14 下午4:09
 */
@Component
public class ChannelInit extends ChannelInitializer<SocketChannel> {
    private static final Logger logger = LogManager.getLogger(ChannelInit.class);

    private final NettyIdle nettyIdle;

    public ChannelInit(NettyIdle nettyIdle) {
        this.nettyIdle = nettyIdle;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //使用 IdleStateHandler 进行心跳检测 以秒为单位
        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline.addLast(new IdleStateHandler(nettyIdle.getReadIdleTimeout(), nettyIdle.getWriteIdleTimeout(), nettyIdle.getAllIdleTimeout(), TimeUnit.SECONDS));
        pipeline.addLast(new ProtocolDetectHandler());
        pipeline.addLast(new ExceptionHandler());
        pipeline.addLast(new NettyServerHandler());
    }
}
